import Taro from '@tarojs/taro'
import {View, Text, Image} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import {AtButton, AtInput} from 'taro-ui'
import qiniuUploader from '../../utils/qiniuUploader'
import config from '../../config'
import validator from 'validator.tool'

import './index.less'

@connect(state => ({
  loading: state.loading.effects['customer/register'],
  customer: state.customer,
}))
export default class Index extends Taro.Component {

  config = {
    navigationBarTitleText: '绑定'
  }

  constructor () {
    super(...arguments)

    // this.state = {
    //   phone: '18352513572',
    //   code: '1234',
    //   name: '看看',
    //   company: '西梅',
    //   position: '工程师',
    //   biz_card_front: 'http://img.cangshi-group.com/tmp/wx49159ebe53978f1b.o6zAJs1G20PDmzf4tPHVf2uXmNY8.oNTaNOpqhJS0f242c38ae60b7136101aee52613af78b.jpeg',
    //   biz_card_back: 'http://img.cangshi-group.com/tmp/wx49159ebe53978f1b.o6zAJs1G20PDmzf4tPHVf2uXmNY8.LEeh5FDoyEEq78854407d4d51a5cb74eb8db64cefbcd.jpg',
    //   disabled: false,
    //   second: 60,
    // }
    this.state = {
      phone: '',
      code: '',
      name: '',
      company: '',
      position: '',
      biz_card_front: '',
      biz_card_back: '',
      disabled: false,
      second: 60,
    }
  }

  componentDidMount() {
  }

  // TODO upate
  componentWillReceiveProps(nextProps) {}

  // navigateTo = url => {
  //   Taro.navigateTo({url})
  // }

  onInputChange = (stateName, value) => {
    this.setState({
      [stateName]: value
    })
  }

  sendCode = () => {
    const {phone, disabled} = this.state;

    // validate phone
    const v = new validator();
    if (!v.isPhone(phone)) {
      Taro.showToast({
        title: '请输入正确的手机号码',
        icon: 'none',
        duration: 1000,
      });
      return;
    }

    if (disabled) {
      return;
    }

    this.setState({
      disabled: true
    });

    // 倒计时
    const timer = setInterval(() => {
      if (this.state.second > 0) {
        this.setState({
          second: this.state.second - 1
        })
      } else {
        this.setState({
          second: 60,
          disabled: false
        });
        clearInterval(timer)
      }
    }, 1000);

    this.props.dispatch({
      type: 'customer/sms',
      payload: {
        phone,
      },
    });
  }

  onUpload = (imgName) => {
    let self = this;
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res && res.tempFilePaths[0];
        qiniuUploader.upload(filePath, (res) => {
          self.setState({
            [imgName]: res.imageURL,
          });
        }, (error) => {
          console.log('error: ' + error);
        }, {
          region: 'ECN',
          domain: config.qiniuConfig.baseExternalLink, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
          // key: 'customFileName.jpg', // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
          // 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
          // uptoken: '[yourTokenString]', // 由其他程序生成七牛 uptoken
          // uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
          // uptokenFunc: function() {return '[yourTokenString]';}
          uptoken: config.qiniuConfig.token, // 由其他程序生成七牛 uptoken
        }, (res) => {
          console.log('上传进度', res.progress)
          console.log('已经上传的数据长度', res.totalBytesSent)
          console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
          Taro.showToast({
            title: res.progress + '% 上传中...',
            icon: 'loading',
          });
        });
      }
    })
  }

  onRegister = () => {
    const {phone, code, name, company, position, biz_card_front, biz_card_back} = this.state;

    // validate
    const v = new validator();
    let title = '';
    if (!v.isPhone(phone)) {
      title = '请输入正确的手机号码';
    } else if (!code) {
      title = '请输入验证码';
    } else if (!name) {
      title = '请输入姓名';
    } else if (!company) {
      title = '请输入公司名称';
    } else if (!position) {
      title = '请输入职位名称';
    } else if (!biz_card_front) {
      title = '请上传名片正面';
    } else if (!biz_card_back) {
      title = '请上传名片背面';
    }
    if (title) {
      Taro.showToast({
        title,
        icon: 'none',
        duration: 1000,
      });
      return;
    }

    // do
    this.props.dispatch({
      type: 'customer/register',
      payload: {
        phone,
        code,
        name,
        company,
        position,
        biz_card_front,
        biz_card_back,
        openid: Taro.getStorageSync('openid'),
      },
    });
  }

  render() {
    const {loading} = this.props;
    const {phone, code, name, company, position, biz_card_front, biz_card_back, disabled, second} = this.state;
    const tipText = disabled ? `${second}s后重试` : '发送验证码';

    return (
      <View className='container'>
        <Text className='base-title'>绑定</Text>
        <Text className='title-des'>您尚未绑定手机，绑定后可使用更多功能</Text>
        <View className='form'>
          <AtInput
            name='phone'
            type='phone'
            placeholder='手机'
            value={phone}
            onChange={this.onInputChange.bind(this, 'phone')}
          />
          <AtInput
            name='code'
            type='number'
            placeholder='请输入验证码'
            value={code}
            onChange={this.onInputChange.bind(this, 'code')}
          >
            <View
              style={{
                'color': disabled ? '#FF4949' : '',
                'fontSize': '12px',
                'width': '90px'
              }}
              onClick={this.sendCode.bind(this)}
            >
              {tipText}
            </View>
          </AtInput>
          <AtInput
            name='name'
            type='text'
            placeholder='姓名'
            value={name}
            onChange={this.onInputChange.bind(this, 'name')}
          />
          <AtInput
            name='company'
            type='text'
            placeholder='公司'
            value={company}
            onChange={this.onInputChange.bind(this, 'company')}
          />
          <AtInput
            name='position'
            type='text'
            placeholder='职位'
            value={position}
            onChange={this.onInputChange.bind(this, 'position')}
          />
          <View className="upload-group">
            <View className="upload-wrapper">
              <View className="upload" onClick={this.onUpload.bind(this, 'biz_card_front')}>
                {
                  biz_card_front
                    ? <Image mode='widthFix' className="img" src={biz_card_front} />
                    : <Text className="text">名片正面</Text>
                }
              </View>
            </View>
            <View className="gap" />
            <View className="upload-wrapper">
              <View className="upload" onClick={this.onUpload.bind(this, 'biz_card_back')}>
                {
                  biz_card_back
                    ? <Image mode='widthFix' className="img" src={biz_card_back} />
                    : <Text className="text">名片背面</Text>
                }
              </View>
            </View>
          </View>
          <AtButton loading={loading} customStyle={{marginTop: '20px', color: '#fff', background: '#8A9DEA', border: 'none'}} type='primary' onClick={this.onRegister}>提交</AtButton>
        </View>
      </View>
    )
  }
}

